/* eslint-disable no-unreachable */
'use strict'

const Service = require('egg').Service
const dayjs = require('dayjs')

// 用户信息要返回的字段
const attributes = ['id', 'open_id', 'nick_name', 'avatar_url', 'phone', 'is_root', 'status', 'logged_at']

class UserService extends Service {
  // 小程序登录
  async wx_login(values) {
    const { model, helper } = this.ctx

    // 组装用户查询参数
    const where = {}
    if (values.unionId) {
      where.union_id = values.union_id
    } else {
      where.open_id = values.open_id
    }
    return await model.User.findOne({ where, attributes })
      .then(async user => {
        const logged_at = dayjs().format('YYYY-MM-DD HH:mm:ss')
        values.logged_at = logged_at
        // 如果找到了用户更新用户信息
        if (user) {
          await user.update(values, { where: { id: user.id } })
          const data = user.toJSON()
          data.logged_at = logged_at
          return data
        }
        helper.failed(1004, where, '用户不存在')
        return false
      })
      .catch(error => {
        helper.failed(1001, null, error.errors[0]?.message)
        return false
      })
  }

  // 用户名密码登录
  async login(params) {
    const { model, helper } = this.ctx
    const where = {
      phone: params.phone,
      password: params.password
    }
    console.log('登录参数', params)
    return await model.User.findOne({ where, attributes })
      .then(async user => {
        const logged_at = dayjs().format('YYYY-MM-DD HH:mm:ss')
        params.logged_at = logged_at
        // 如果找到了用户更新用户信息
        if (user) {
          if (user.status !== 1) {
            helper.failed(2002, null, '用户被禁用')
            return false
          }
          await user.update(params, { where: { id: user.id } })
          // 返回用户信息
          const data = user.toJSON()
          data.logged_at = logged_at
          return data
        }
        helper.failed(1004, null, '用户名或密码错误2')
        return false
      })
      .catch(error => {
        helper.failed(1001, null, error.errors[0]?.message)
        return false
      })
  }

  // 查询所有用户列表
  async getUserList(params) {
    const { model, helper } = this.ctx
    const currentPage = params?.pageIndex ?? 1
    const pageSize = params?.pageSize ?? 50

    const { Op } = require('sequelize')
    const where = {}
    if (params.account) {
      where.phone = {
        [Op.like]: `%${params.account}%`
      }
    }
    if (params.status !== undefined && params.status !== null) {
      where.status = params.status
    }

    return await model.User.findAndCountAll({
      where,
      offset: (currentPage - 1) * pageSize, // 计算分页偏移量
      limit: pageSize,
      attributes
    })
      .then(async result => {
        if (result) {
          return {
            list: result.rows,
            total: result.count
          }
        }
        helper.failed(1004, null, '查询用户列表失败')
        return false
      })
      .catch(async error => {
        helper.failed(1001, null, error.errors[0]?.message)
        return false
      })
  }

  // 新建用户
  async createUser(params) {
    const { model, helper } = this.ctx
    // const { open_id, nick_name, avatar_url, phone, gender, province, city, language } = params
    params.created_at = dayjs().format('YYYY-MM-DD HH:mm:ss')
    params.updated_at = dayjs().format('YYYY-MM-DD HH:mm:ss')
    console.log('参数', params)
    return await model.User.create(params)
      .then(async data => {
        if (data) {
          return data
        }
        helper.failed(1005, null, '用户注册失败')
        return false
      })
      .catch(async error => {
        helper.failed(1001, params, error.errors[0]?.message)
        return false
      })
  }

  // 修改密码
  async changePassword(params) {
    const { model, helper } = this.ctx
    const where = {
      id: params.id,
      password: params.password
    }

    const values = {
      password: params.new_password
    }
    return await model.User.findOne({ where })
      .then(async user => {
        if (user) {
          return await user.update(values)
            .then(async data => {
              if (data) {
                return data
              }
              helper.failed(1006, null, '修改密码失败')
              return false
            })
            .catch(async error => {
              helper.failed(1001, null, error.errors[0]?.message)
              return false
            })
        }
        helper.failed(1004, null, '用户名或密码错误')
        return false
      })
      .catch(async error => {
        helper.failed(1001, null, error.errors[0]?.message)
        return false
      })
  }

  // 编辑用户
  async editUser(params) {
    const { model, helper } = this.ctx

    return await model.User.findByPk(params.id)
      .then(async result => {
        if (result) {
          return await result.update(params)
            .then(async data => {
              if (data) {
                return data
              }
              helper.failed(1006, null, '编辑用户失败')
              return false
            })
            .catch(async error => {
              helper.failed(1001, null, error.errors[0]?.message)
              return false
            })
        }
        helper.failed(1004, null, '用户不存在')
        return false
      })
      .catch(async error => {
        helper.failed(1001, null, error.errors[0]?.message)
        return false
      })
  }

  // 删除用户
  async deleteUser(params) {
    const { model, helper } = this.ctx

    return await model.User.findByPk(params.id)
      .then(async result => {
        if (result) {
          if (result.is_root === 1) {
            helper.failed(1002, null, '不能删除超级管理员')
            return false
          }
          return await result.destroy()
            .then(async data => {
              if (data) {
                return data
              }
              helper.failed(1007, null, '删除用户失败')
              return false
            })
            .catch(async error => {
              helper.failed(1001, null, error.errors[0]?.message)
              return false
            })
        }
        helper.failed(1004, null, '用户不存在')
        return false
      })
      .catch(async error => {
        helper.failed(1001, null, error.errors[0]?.message)
        return false
      })
  }

  // 获取用户信息
  async info(id) {
    const { model, helper } = this.ctx

    return await model.User.findOne({
      where: { id },
      attributes
    })
      .then(async user => {
        if (user) {
          return user
        }
        helper.failed(1004, null, '用户不存在')
        return false
      })
      .catch(error => {
        console.log('错误.....', error)
        helper.failed(1001, null, error.errors[0]?.message)
        return false
      })
  }
}

module.exports = UserService
